import { PostService, UserService, PuzzleService, WordService } from "@/utils/prisma"
import { NextResponse } from "next/server"
import { getWord, toPzuuleAi, translate } from "./action"


export async function POST(request: Request) {
  const { action, params } = await request.json()
  try {
    switch (action) {
      case "init": {
        const { chat_id } = params
        // const allPost = await PostService.getPostById(chat_id)
        // todo 在这里传入
        let page = 1
        const allPost = await PostService.getPagePostById(chat_id, page, 30) // 获取第一页，每页10条 content

        return NextResponse.json({
          data: allPost,
          status: 200,
        })
      }
      case "check": {
        //判断是否收藏
        const { id, chat_id } = params
        const booklist = await UserService.getBook(id) as any
        if (booklist.bookshelf) {
          const exists = booklist.bookshelf.some((book: any) => book === chat_id);
          return NextResponse.json({
            data: { exists },
            status: 200,
          })
        } else {
          return NextResponse.json({
            data: { exists: false },
            status: 200,
          })
        }
      }
      case "read": {
        const { text } = params
        const lang = "uk"

        const baiduUrl = `https://fanyi.baidu.com/gettts?lan=${lang}&text=${encodeURIComponent(
          text
        )}&spd=3`
        const response = await fetch(baiduUrl, {
          method: "GET",
          headers: {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36",
            "Referer": `https://fanyi.baidu.com/mtpe-individual/multimodal?query=${encodeURIComponent(text)}&lang=en2zh`,
          }
        }).then(res => {
          return res
        })
        const audioBuffer = await response.arrayBuffer()
        return new Response(audioBuffer, {
          headers: {
            "Content-Type": "audio/mpeg",
            "Content-Length": audioBuffer.byteLength.toString(),
          },
        })
      }
      case "word": {
        const { id, text } = params
        // console.log(id, text)
        const word = await getWord(text.replace(/[^a-zA-Z]/g, ''))
        const cleanedText = text.replace(/[^a-zA-Z]/g, '').toLowerCase();
        if (id && word[0] && word[0].k.toLowerCase() === cleanedText) {
          // console.log(word[0].k.toLowerCase() === cleanedText); // true
          console.log(word[0])
          WordService.createWord(id, { en: word[0].k, zh: word[0].v })
        }
        return NextResponse.json({
          data: word,
          status: 200,
        })
      }

      case "update": {
        const { chat_id, readTxt } = params
        await PostService.updatePost(chat_id, { content: readTxt })
        return NextResponse.json({
          data: [],
          status: 200,
        })
      }
      case "translate": {
        const { text } = params
        // console.log(text)
        const cleanText = text.replace(/\n/g, "").replace(/\r/g, ""); // 删除换行符
        const translatedText = await translate(cleanText, "zh")

        return NextResponse.json({
          data: { text: translatedText },
          status: 200,
        })
      }
      case "quzzle": {
        const { chatID } = params
        const quzzle = await PuzzleService.getPuzzleId(chatID)
        // console.log(quzzle)
        if (quzzle) {
          return NextResponse.json({
            data: quzzle.content,
            status: 200,
          })
        }
        return NextResponse.json({
          data: [],
          status: 200,
        })
      }
      case "createQuzzle": {
        const { chatID, text } = params
        const createQuzzle = await toPzuuleAi(text)//ai创建题目
        PuzzleService.createPuzlle(chatID, createQuzzle)//先存数据库
        return NextResponse.json({
          data: createQuzzle,
          status: 200,
        })

      }
      default:
        return NextResponse.json({ status: 400, error: "Invalid action" })
    }
  } catch (error) {
    console.error(error)
    return NextResponse.json({
      status: 500,
      error: "Failed to process request",
    })
  }
}

